package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jbp.dao.GiftShopDao;
import com.jbp.exception.RRException;
import com.jbp.model.*;
import com.jbp.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商城礼物(GiftShop)表服务实现类
 * @author cc
 * @since 2020-06-20 08:53:26
 */
@SuppressWarnings("ALL")
@Service
public class GiftShopServiceImpl extends ServiceImpl<GiftShopDao, GiftShop> implements GiftShopService {
    @Autowired
    private GiftService giftService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private WalletRecordService walletRecordService;
    @Autowired
    private SendGiftRecordService sendGiftRecordService;

    @Autowired
    private RankProportionService rankProportionService;

    @Autowired
    private RoomUserWheatService roomUserWheatService;

    @Autowired
    private RoomWheatService roomWheatService;

    @Autowired
    private UserService userService;

    @Autowired
    private IncomeService incomeService;
    @Autowired
    private UserNobilityService userNobilityService;

    @Autowired
    private UserDailySendgiftRecordService userDailySendgiftRecordService;

    @Autowired
    private UserLevelService userLevelService;

    @Autowired
    private UserSendGiftLogService userSendGiftLogService;

    @Override
    public List<GiftShop> allGift() {
        QueryWrapper<GiftShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        List<GiftShop> list = this.list(queryWrapper);
        list.forEach(giftShop -> {
            Gift gift = giftService.getById(giftShop.getGiftId());
            giftShop.setGiftName(gift.getName());
            giftShop.setGiftCoin(gift.getCoin());
            giftShop.setGiftCartoonUrl(gift.getCartoonUrl());
            giftShop.setGiftImgUrl(gift.getImgUrl());
        });
        return list;
    }

    /**商店送礼*/
    @Override
    @Transactional
    public synchronized void  sendShopGift(Map<String, Object> params) {
        //房间Id
        Integer roomId = (Integer) params.get("roomId");
        //我的id
        Integer userId = (Integer) params.get("userId");
        //礼物id
        Integer giftId = (Integer) params.get("giftId");
        //礼物数量
        Integer num = (Integer) params.get("num");
        if (num==null || num<=0) {
            throw new RRException("礼物数量错误");
        }
        //送给目标用户id，以，分隔
        String otherId = (String) params.get("otherId");
        ArrayList<Integer> otherIds = new ArrayList<>();
        for (String idStr : otherId.split(",")) {
            if (idStr!=null) {
                otherIds.add(Integer.parseInt(idStr));
            }
        }

        //检查目标用户
        if (otherIds.size()==0) {
            throw new RRException("目标用户错误");
        }

        //检查房间id
        Room room = roomService.getById(roomId);
        if (room == null) {
            throw new RRException("房间错误");
        }
        //检查礼物id
        Gift gift = giftService.getById(giftId);
        if (gift == null) {
            throw new RRException("礼物错误");
        }
        //检查余额
        Wallet myWallet = walletService.getByUserId(userId);
        if (myWallet == null) {
            throw new RRException("账户异常");
        }
        //总价 = 礼物单价*数量*人数
        int totalPrice = gift.getCoin() * num * otherIds.size();
        if (myWallet.getXinzuan().doubleValue()<totalPrice) {
            throw new RRException("余额不足");
        }
        double afterBalance = myWallet.getXinzuan().doubleValue() - totalPrice;

        //自己添加钱包变动记录
        WalletRecord walletRecordMe = new WalletRecord();
        walletRecordMe.setOperationType("send_gift");
        walletRecordMe.setCoinType("xinzuan");
        walletRecordMe.setAddType("sub");
        walletRecordMe.setBeforeBalance(myWallet.getXinzuan());
        walletRecordMe.setChangeBalance(BigDecimal.valueOf(totalPrice));
        walletRecordMe.setAfterBalance(BigDecimal.valueOf(afterBalance));
        walletRecordMe.setUserId(userId);
        walletRecordService.save(walletRecordMe);

        //百万奖池金额处理
        rankProportionService.addPrizePoolAmount(walletRecordMe.getChangeBalance());



        //自己扣钱
        myWallet.setXinzuan(BigDecimal.valueOf(afterBalance));
        walletService.updateWithLock(myWallet);

        otherIds.forEach(otherUserId->{
            //别人钱包变动记录
            Wallet otherWallet = walletService.getByUserId(otherUserId);
            double changeBalance = gift.getCoin() * num * 0.7d;
            double afterAixin = otherWallet.getAixin().doubleValue() + changeBalance;

            WalletRecord walletRecordOther = new WalletRecord();
            walletRecordOther.setOperationType("recive_gift");
            walletRecordOther.setCoinType("aixin");
            walletRecordOther.setAddType("add");
            walletRecordOther.setBeforeBalance(otherWallet.getAixin());
            walletRecordOther.setChangeBalance(BigDecimal.valueOf(changeBalance));
            walletRecordOther.setAfterBalance(BigDecimal.valueOf(afterAixin));
            walletRecordOther.setUserId(otherUserId);
            walletRecordService.save(walletRecordOther);

            //别人爱心增加
            otherWallet.setAixin(BigDecimal.valueOf(afterAixin));
            walletService.updateWithLock(otherWallet);

            //送礼记录
            SendGiftRecord giftRecord = new SendGiftRecord();
            giftRecord.setGiftId(gift.getId());
            giftRecord.setGiftName(gift.getName());
            giftRecord.setGiftImg(gift.getImgUrl());
            giftRecord.setGiftPrice(gift.getCoin());
            giftRecord.setNum(num);
            giftRecord.setFromUserId(userId);
            giftRecord.setToUserId(otherUserId);
            giftRecord.setRoomId(roomId);
            giftRecord.setType("shop");
            sendGiftRecordService.save(giftRecord);

            roomWheatService.addCharm(otherUserId, roomId, gift.getCoin() * num);

            userDailySendgiftRecordService.updateSendGiftRecord(userId, otherUserId, gift.getCoin() * num, roomId, "shop");

            //送礼消息
            String log = gift.getName()+"("+gift.getCoin()+")*"+num+ " 总计:"+gift.getCoin() * num;
            userSendGiftLogService.sendGiftMsg(userId, otherUserId, log);

            UserSendGiftLog userSendGiftLog = new UserSendGiftLog();
            userSendGiftLog.setFromUserId(userId);
            userSendGiftLog.setToUserId(otherUserId);
            userSendGiftLog.setContent(log);
            userSendGiftLog.setType("shop");
            userSendGiftLog.setRoomId(roomId);
            userSendGiftLog.setTotalPrice(gift.getCoin() * num);
            userSendGiftLog.setImg(gift.getImgUrl());
            userSendGiftLogService.save(userSendGiftLog);
        });

        //发放流水分成
        incomeService.deployIncome(room.getId(), totalPrice, "shop");

        userNobilityService.addScore(userId, totalPrice);

        //房间人气值增加
        room.setMood(room.getMood()+totalPrice);
        roomService.updateById(room);

        //自己经验值增加
        userLevelService.addScore(userId, totalPrice);
    }
}
